<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="dataInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column label="用户状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="upDateUser(scope.row)"
            ></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="分配角色" :visible.sync="setRolesVisible" width="50%" @close="closeAndSet">
        <div>
          <p>当前的用户：{{rolesInfo.username}}</p>
          <p>当前的角色：{{rolesInfo.role_name}}</p>
          <p>
            分配角色：
            <el-select v-model="selectRolesId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRolesVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoles">确 定</el-button>
        </span>
      </el-dialog>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="dataInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="dataInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户表单 -->
    <el-dialog title="添加用户信息" :visible.sync="addDialogVisible" width="50%" @close="addFormReset">
      <el-form
        ref="userAddRef"
        :rules="addUserRules"
        :model="user"
        label-position="left"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="user.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="user.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addButReset">取 消</el-button>
        <el-button type="primary" @click="trueAndAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户表单 -->
    <el-dialog title="编辑用户信息" :visible.sync="updataDialogVisible" width="50%">
      <el-form
        ref="userUpdataRef"
        :rules="updataUserRules"
        :model="userUpdata"
        label-position="left"
        label-width="80px"
        @close="updataFormReset"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userUpdata.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userUpdata.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userUpdata.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updataDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="trueAndUpDateUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的邮箱"));
    };
    //验证手机号码的规则
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[34578]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      //返回一个错误提示
      cb(new Error("请输入合法的手机号码"));
    };
    return {
      dataInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      setRolesVisible: false,
      user: {
        password: "",
        username: "",
        email: "",
        mobile: ""
      },
      userUpdata: {},
      addUserRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      updataUserRules: {
        email: [
          { message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      userList: [],
      total: 0,
      value: true,
      addDialogVisible: false,
      updataDialogVisible: false,
      rolesInfo: {},
      rolesList: [],
      selectRolesId: ""
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async saveRoles() {
      if (!this.selectRolesId) {
        return this.$message.error("请选择要分配的角色");
      }
      const { data: res } = await this.$http.put(
        `users/${this.rolesInfo.id}/role`,
        {
          rid: this.selectRolesId
        }
      );
      if (res.meta.status != 200) {
        return this.$message.error("分配角色失败");
      }
      this.getUserList();
      this.setRolesVisible = false;
    },
    async setRoles(rolesInfo) {
      this.rolesInfo = rolesInfo;
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status != 200) {
        this.$message.error("获取角色列表失败");
      } else {
        this.rolesList = res.data;
      }
      this.setRolesVisible = true;
    },
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.dataInfo
      });
      if (res.meta.status != 200) {
        this.$message.error("获取信息失败");
      } else {
        this.userList = res.data.users;
        this.total = res.data.total;
      }
    },
    handleSizeChange(pagesize) {
      this.dataInfo.pagesize = pagesize;
      this.getUserList();
    },
    handleCurrentChange(nowpage) {
      this.dataInfo.pagenum = nowpage;
      this.getUserList();
    },
    async stateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("更新用户状态失败");
      }
    },
    async upDateUser(userInfo) {
      const { data: res } = await this.$http.get(`users/${userInfo.id}`);
      if (res.meta.status != 200) {
        this.$message.error("获取信息失败");
      } else {
        this.userUpdata = res.data;
        this.updataDialogVisible = true;
      }
    },
    trueAndAddUser() {
      this.$refs.userAddRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post("users", this.user);
          if (res.meta.status != 201) {
            this.$message.error("添加失败");
          } else {
            this.$message.success("添加成功");
            this.addDialogVisible = false;
            this.getUserList();
          }
        } else {
          this.$message.warning("请输入正确格式");
        }
      });
    },
    async open(userInfo) {
      const result = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (result == "confirm") {
        const { data: res } = await this.$http.delete(`users/${userInfo.id}`);
        if (res.meta.status != 200) {
          this.$message.error("删除失败");
        } else {
          this.$message.success("删除成功");
          this.getUserList();
        }
      } else {
        this.$message.info("已经取消删除");
      }
    },
    addButReset() {
      this.$refs.userAddRef.resetFields();
      this.addDialogVisible = false;
    },
    trueAndUpDateUser() {
      this.$refs.userUpdataRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "users/" + this.userUpdata.id,
            {
              email: this.userUpdata.email,
              mobile: this.userUpdata.mobile
            }
          );
          if (res.meta.status != 200) {
            this.$message.error("修改失败");
          }
          this.updataDialogVisible = false;
          this.getUserList();
          this.$message.success("修改成功");
        }
      });
    },
    addFormReset() {
      this.$refs.userAddRef.resetFields();
    },
    updataFormReset() {
      this.$refs.userUpdataRef.resetFields();
    },
    closeAndSet() {
      this.selectRolesId = "";
      this.rolesInfo = {};
    }
  }
};
</script>
<style lang="less" scoped>
</style>